package com.recipedb.sprint.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 简化版BashRunner - 适合本地开发环境
 */
@Slf4j
@Component
public class BashRunner {

    private final StringRedisTemplate redisTemplate;

    // 相对路径，适合本地开发
    private final String SCRIPT_PATH = "src/main/bash/run_llm.sh";

    public BashRunner(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 异步执行Bash脚本
     */
    public CompletableFuture<Void> runBashScriptAsync(String redisKey, String model, String prompt) {
        return CompletableFuture.runAsync(() -> runBashScript(redisKey, model, prompt));
    }

    /**
     * 执行Bash脚本
     */
    public void runBashScript(String redisKey, String model, String prompt) {
        log.info("执行Bash脚本 - redisKey: {}, model: {}", redisKey, model);

        try {
            File scriptFile = new File(SCRIPT_PATH);

            if (!scriptFile.exists()) {
                log.error("脚本文件不存在: {}", scriptFile.getAbsolutePath());
                return;
            }

            // 确保脚本可执行
            if (!scriptFile.canExecute()) {
                scriptFile.setExecutable(true);
            }

            ProcessBuilder pb = new ProcessBuilder(
                    "bash",
                    scriptFile.getAbsolutePath(),
                    model,
                    redisKey
            );

            pb.redirectErrorStream(true);
            Process process = pb.start();

            // 写入prompt
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()))) {
                writer.write(prompt);
                writer.flush();
                log.info("Prompt已写入，长度: {}", prompt.length());
            }

            // 读取输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.debug("Bash输出: {}", line);
                }
            }

            int exitCode = process.waitFor();
            log.info("Bash脚本退出码: {}", exitCode);

        } catch (Exception e) {
            log.error("Bash执行失败: {}", e.getMessage());
            throw new RuntimeException("Bash脚本执行失败", e);
        }
    }
}